<template>
  <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="uploadFileUrl"
      :data="data"
      :file-list="data.fileList"
      list-type="picture-card"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="1"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :auto-upload="false"
      :headers="headers"
  >
    <template #trigger>
      <el-icon><Plus /></el-icon>
    </template>
  </el-upload>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { getToken } from '@/utils/auth'
import { showConfirm, toast } from '@/utils/common'
import { Plus } from '@element-plus/icons-vue'
// import { defineProps, defineEmits } from 'vue'

const limit = 1
const props = defineProps({
  fileList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:fileList'])

const data = reactive({
  fileName: 'file',
  fileList: props.fileList,
})

const uploadRef = ref(null)
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/uploadOSS')
const headers = ref({ Authorization: 'Bearer ' + getToken() })

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  toast(`图片最多只能上传${limit}张，你选择了${files.length}张图片`)
}

const beforeRemove = (uploadFile, uploadFiles) => {
  showConfirm(`确定要取消上传文件 ${uploadFile.name} ？`)
      .then(() => {
        toast('取消上传成功')
        return true
      })
      .catch(() => {
        toast('取消上传失败')
        return false
      })
}

// 上传文件成功
const uploadSuccess = (response) => {
  if (response.code === 200) {
    toast('上传成功')
    console.log('response', response)
    data.fileList.push({
      name: response.newFileName,
      url: response.url,
    })
    emit('update:fileList', data.fileList)
  } else {
    toast(response.msg)
  }
}

const submitUpload = () => {
  // 手动提交
  uploadRef.value.submit()
}

const resetUpload = () => {
  // 重置上传
  uploadRef.value.clearFiles()
}

// 暴露子组件的方法给父组件
defineExpose({
  submitUpload,
  resetUpload,
})

// 监听 fileList 的变化
watch(
    () => data.fileList,
    (newFileList) => {
      emit('update:fileList', newFileList)
    },
)
</script>
